package com.hustcad.es.config;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangwen on 2019/9/25 14:57
 */
@Configuration
/*@AutoConfigureAfter(ElasticSearchConfig.class)*/
public class EsConfiguration {

    private static List<HttpHost> hostList ;
    /**
     * 集群地址，多个用,隔开
     */
    @Value("${esconfig.host}")
    private String hosts;

    /**
     * 使用的端口号
     */
    @Value("${esconfig.port}")
    private int port;

    /**
     * 使用的协议
     */
    @Value("${esconfig.schema}")
    private String schema;

    /**
     * 连接超时时间
     */
    @Value("${esconfig.connectTimeOut}")
    private int connectTimeOut;

    /**
     * 连接超时时间
     */
    @Value("${esconfig.socketTimeOut}")
    private int socketTimeOut;

    /**
     * 获取连接的超时时间
     */
    @Value("${esconfig.connectionRequestTimeOut}")
    private int connectionRequestTimeOut;

    /**
     * 最大连接数
     */
    @Value("${esconfig.maxConnectNum}")
    private int maxConnectNum;

    /**
     * 最大路由连接数
     */
    @Value("${esconfig.maxConnectPerRoute}")
    private int maxConnectPerRoute;

    @Bean
    public RestHighLevelClient client() {
        hostList = new ArrayList<>();
        String[] hostStrs = hosts.split(",");
        for (String host : hostStrs) {
            hostList.add(new HttpHost(host, port, schema));
        }
        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        // lamber表达式写法
        builder.setRequestConfigCallback((RequestConfig.Builder requestConfigBuilder) -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });


        builder.setHttpClientConfigCallback((HttpAsyncClientBuilder httpClientBuilder) -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }

}
